<template>
  <div class="notice-container">
    <!-- 顶部导航栏 -->
    <div class="notice-header">
      <div class="header-left">
        <div class="back-button" @click="goBack">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path d="M15 18L9 12L15 6" stroke="#333" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
      </div>
      <div class="header-title">
        <h1>全部互动消息</h1>
      </div>
      <div class="header-right">
      </div>
    </div>

    <!-- 通知列表 -->
    <div class="notice-list">
      <div v-for="notice in notices" :key="notice.id" class="notice-item" @click="handleNoticeClick(notice)">
        <div class="notice-avatar">
          <img :src="notice.user.avatar" :alt="notice.user.name" />
        </div>
        
        <div class="notice-content">
          <div class="user-name">{{ notice.user.name }}</div>
          <div class="notice-text">
            <span v-if="notice.type === 'like'" class="like-text">{{ notice.likeEmoji }}</span>
            <span v-else-if="notice.type === 'comment'" class="comment-text">
              <span v-if="notice.isReply === 1" class="reply-label">回复了 {{ notice.replyUsername }}:</span>
              <span class="comment-content">{{ notice.content }}</span>
            </span>
          </div>
          <div class="notice-time">{{ notice.time }}</div>
        </div>
        
        <!-- 右侧缩略图 -->
        <div v-if="notice.moment && ((notice.moment.images && notice.moment.images.length > 0) || notice.moment.video)" class="notice-thumbnail">
          <img 
            v-if="notice.moment.images && notice.moment.images.length > 0" 
            :src="notice.moment.images[0]" 
            alt="缩略图"
            class="thumbnail-image"
          />
          <video 
            v-else-if="notice.moment.video"
            :src="notice.moment.video" 
            :poster="notice.moment.videoPoster"
            class="thumbnail-video"
            muted
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/utils/http'
import { ElMessage } from 'element-plus'

interface User {
  id: number
  name: string
  avatar: string
}

interface Moment {
  id: number
  text?: string
  images?: string[]
  video?: string
  videoPoster?: string
}

interface Notice {
  id: number
  type: 'like' | 'comment'
  user: User
  content?: string // 评论内容
  likeEmoji?: string // 点赞表情
  moment?: Moment // 关联的朋友圈内容
  time: string
  momentId?: number
  isReply?: number // 0: 普通评论, 1: 回复评论
  replyUserId?: string
  replyUsername?: string
}

const router = useRouter()

// 数据状态
const notices = ref<Notice[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)

// 用户ID
const noticeUserId = ref()

// 返回上一页
const goBack = () => {
  router.back()
}

// 格式化时间
const formatTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  const now = new Date()
  
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  
  const currentYear = now.getFullYear()
  
  if (year === currentYear) {
    return `${month}月${day}日 ${hour < 12 ? '上午' : '下午'}${hour % 12 || 12}:${minute.toString().padStart(2, '0')}`
  } else {
    return `${year}年${month}月${day}日 ${hour < 12 ? '上午' : '下午'}${hour % 12 || 12}:${minute.toString().padStart(2, '0')}`
  }
}

// 转换后端数据为前端格式
const transformNoticeData = (backendData: any): Notice => {
  const notice: Notice = {
    id: backendData.id,
    type: backendData.type === 0 ? 'like' : 'comment',
    user: {
      id: backendData.userId,
      name: backendData.username,
      avatar: backendData.avatar || 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=50&h=50&fit=crop&crop=face'
    },
    time: formatTime(backendData.createTime),
    momentId: backendData.momentId,
    isReply: backendData.isReply,
    replyUserId: backendData.replyUserId,
    replyUsername: backendData.replyUsername
  }

  if (backendData.type === 0) {
    // 点赞类型
    notice.likeEmoji = '♡'
  } else {
    // 评论类型
    notice.content = backendData.content
  }

  // 处理朋友圈缩略图
  if (backendData.fileUrl) {
    notice.moment = {
      id: backendData.momentId
    }
    
    // 判断是图片还是视频（这里需要根据实际情况判断）
    if (backendData.fileUrl.includes('mp4') || backendData.fileUrl.includes('video')) {
      notice.moment.video = backendData.fileUrl
    } else {
      // 如果是多张图片，取第一张作为缩略图
      const imageUrls = backendData.fileUrl.split(',')
      notice.moment.images = imageUrls.filter((url: string) => url.trim())
    }
  }

  return notice
}

// 获取通知列表
const loadNotices = async (page: number = 1, isLoadMore: boolean = false) => {
  if (loading.value) return
  
  loading.value = true
  try {
    const response = await api.get(`/moments/notice/user/${noticeUserId.value}`, {
      params: {
        pageNo: page,
        pageSize: pageSize.value
      }
    })
    
    if (response.data && response.data.code === 200) {
      const pageData = response.data.data
      const newNotices = pageData.records.map(transformNoticeData)
      
      if (isLoadMore) {
        notices.value.push(...newNotices)
      } else {
        notices.value = newNotices
      }
      
      hasMore.value = pageData.current < pageData.pages
      currentPage.value = pageData.current
    }
  } catch (error) {
    console.error('加载通知失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理通知点击
const handleNoticeClick = (notice: Notice) => {
  console.log(notice.momentId)
  // 跳转到对应的朋友圈详情页
  if (notice.momentId) {
    router.push(`/momentDetail?id=${notice.momentId}`)
  }
}
const getUserIdFromToken = (token: string) => {
  if (!token) return '';
  try {
    const payloadBase64 = token.split('.')[1];
    const decoded = JSON.parse(atob(payloadBase64));
    return decoded.sub; 
  } catch (error) {
    console.error('Token解析失败:', error);
    return '';
  }
};

// 组件挂载时加载数据
onMounted(() => {
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.warning('未检测到登录态，请先登录');
    return;
  }
  noticeUserId.value = getUserIdFromToken(token);
  loadNotices()
})
</script>

<style scoped>
.notice-container {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 顶部导航栏 */
.notice-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #f0f0f0;
  border-bottom: 1px solid #e0e0e0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.header-left,
.header-right {
  width: 60px;
  display: flex;
  align-items: center;
}

.header-left {
  justify-content: flex-start;
}

.header-right {
  justify-content: flex-end;
}

.back-button,
.menu-button {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.back-button:hover,
.menu-button:hover {
  background: rgba(0, 0, 0, 0.05);
}

.header-title {
  flex: 1;
  text-align: center;
}

.header-title h1 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

/* 通知列表 */
.notice-list {
  background: white;
}

.notice-item {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.notice-item:hover {
  background: #f9f9f9;
}

.notice-item:last-child {
  border-bottom: none;
}

.notice-avatar {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 12px;
  flex-shrink: 0;
}

.notice-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.notice-content {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.like-text {
  font-size: 16px;
  color: #333;
}

.comment-text {
  font-size: 15px;
  color: #333;
  line-height: 1.4;
}

.reply-label {
  color: #888;
  margin-right: 4px;
}

.comment-content {
  color: #333;
}

.reply-info {
  color: #888;
  font-size: 13px;
  margin-left: 4px;
}

.notice-time {
  font-size: 13px;
  color: #888;
  margin-top: 2px;
}

/* 右侧缩略图 */
.notice-thumbnail {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;
  margin-left: 12px;
  flex-shrink: 0;
}

.thumbnail-image,
.thumbnail-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .notice-header {
    padding: 10px 12px;
  }
  
  .header-title h1 {
    font-size: 17px;
  }
  
  .notice-item {
    padding: 12px;
  }
  
  .notice-avatar {
    width: 45px;
    height: 45px;
    margin-right: 10px;
  }
  
  .user-name {
    font-size: 15px;
  }
  
  .like-text {
    font-size: 15px;
  }
  
  .comment-text {
    font-size: 14px;
  }
  
  .notice-time {
    font-size: 12px;
  }
  
  .notice-thumbnail {
    width: 50px;
    height: 50px;
    margin-left: 10px;
  }
}
</style>
